package com.hb.znpt.viewmodel;

import android.app.Application;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hb.znpt.adapter.GridImageAdapter;
import com.hb.znpt.bean.LandBean;
import com.hb.znpt.bean.LesseeBean;
import com.hb.znpt.bean.UpdataBean;
import com.hb.znpt.image.GlideEngine;
import com.hb.znpt.model.UploadModel;
import com.hb.znpt.utils.Constants;
import com.hb.znpt.utils.DateUtils;
import com.hb.znpt.utils.LogUtils;
import com.hb.znpt.utils.OssManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.rxjava.rxlife.RxLife;
import com.unitlib.base.base.BaseViewModel;
import com.unitlib.base.utils.SPUtils;
import com.unitlib.base.utils.ToastUtils;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * @Description: 描述
 * @Author: houbing
 * @CreateDate: 2021/9/9 16:57
 */
public class UploadViewModel extends BaseViewModel<UploadModel> {

    public ObservableField<String> lon = new ObservableField<>("");
    public ObservableField<String> lat = new ObservableField<>("");

    public AMapLocationClient mLocationClient = null;

    public AMapLocation mapLocation;

    public LandBean bean;
    public LesseeBean dept;
    public LocalMedia localMedia;

    public UploadViewModel(@NonNull Application application) {
        super(application);
        model = new UploadModel();
    }

    @Override
    public void onCreate() {
        dept = (LesseeBean) intent.getSerializableExtra("dept");
        bean = (LandBean) intent.getSerializableExtra("data");
        AMapLocationClientOption option = getDefaultOption();
        mLocationClient = new AMapLocationClient(context.getApplicationContext());
        mLocationClient.setLocationOption(option);
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation == null || aMapLocation.getErrorCode() != 0)
                    return;
                LogUtils.e(TAG, aMapLocation.toString());
                mapLocation = aMapLocation;
                lon.set(mapLocation.getLongitude() + "");
                lat.set(mapLocation.getLatitude() + "");
            }
        });
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption clientOption = new AMapLocationClientOption();
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        clientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        clientOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        clientOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        clientOption.setInterval(1000);//可选，设置定位间隔。默认为2秒
        clientOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        clientOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        clientOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        clientOption.setSensorEnable(true);//可选，设置是否使用传感器。默认是false
        clientOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        clientOption.setLocationCacheEnable(false); //可选，设置是否使用缓存定位，默认为true
        return clientOption;
    }

    public void photo(GridImageAdapter adapter) {
        PictureSelector.create(activity)
                .openCamera(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .isAndroidQTransform(true)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && .isEnableCrop(false);有效,默认处理
                .isDisplayOriginalSize(true)// 是否显示原文件大小，isOriginalImageControl true有效
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .isPreviewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .isEnableCrop(false)// 是否裁剪
                .isCompress(true)// 是否压缩
                .compressQuality(80)// 图片压缩后输出质量
                .isGif(false)// 是否显示gif图片
                .isCropDragSmoothToCenter(true)// 裁剪框拖动时图片自动跟随居中
                .selectionData(adapter.getData())// 是否传入已选图片
                .minimumCompressSize(100)// 小于多少kb的图片不压缩
                .forResult(new PhotoResultCallback(adapter));
    }

    public void submit(View view) {
        getUC().getShowLoadingDialogEvent().call();
        OssManager.getInstance().upload(localMedia.getCompressPath(), new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtils.e(TAG, "上传成功" +
                        "\nobjectKey:" + request.getObjectKey() +
                        "\nETag:" + result.getETag() +
                        "\nRequestId:" + result.getRequestId());
                upload(request.getObjectKey());
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("图片上传失败，请检查手机网络是否畅通！");
                        getUC().getDismissLoadingDialogEvent().call();
                    }
                });
            }
        });
    }

    public void save(View view) {
        UpdataBean updataBean = new UpdataBean(Integer.parseInt(bean.getZwid()),
                SPUtils.getInstance().getString(Constants.SP_USERCARD), lat.get(), lon.get(),
                localMedia.getCompressPath(), bean.getZwmc(), dept.getDeptname(), bean.getZwmj(),
                DateUtils.date2String(new Date(), DateUtils.yyyyMMddHHmmss.get()), 0);
        if (updataBean.saveOrUpdate("zwid = ?", bean.getZwid())) {
            ToastUtils.showShort("保存成功");
            finish();
        }
    }

    public void upload(String url) {
        model.upload(mapLocation.getLatitude(), mapLocation.getLongitude(), url, bean.getZwid() + "")
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    getUC().getDismissLoadingDialogEvent().call();
                })
                .as(RxLife.as(owner))
                .subscribe(bean -> {
                    finish();
                }, error -> {
                    ToastUtils.showShort(error.getMessage());
                });
    }

    private class PhotoResultCallback implements OnResultCallbackListener<LocalMedia> {

        private WeakReference<GridImageAdapter> mAdapterWeakReference;

        public PhotoResultCallback(GridImageAdapter adapter) {
            super();
            this.mAdapterWeakReference = new WeakReference<>(adapter);
        }


        @Override
        public void onResult(List<LocalMedia> result) {
            if (mAdapterWeakReference.get() != null) {
                localMedia = result.get(0);
                mAdapterWeakReference.get().setList(result);
                mAdapterWeakReference.get().notifyDataSetChanged();
            }
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "PictureSelector Cancel");
        }
    }


    @Override
    public void onDestroy() {
        destroyLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationClient = null;
        }
    }
}
